#include <stdio.h>
#include <stdlib.h>
#include "huffman.h"


#define putbit(b) putchar((b) ? '1' : '0')

void myputchar (int c) {
  int i;
  for (i = 7; i >= 0; i--) putbit ((c >> i) & 1);
}

int main (int argc, char *argv[]) {
  int c;
  FILE *f;
  struct huff_code_struct cs;
  
  if (argc == 2) {
    if (!(f = fopen (argv[1], "r"))) {
      printf ("An error occured while opening %s\n", argv[1]);
      exit (EXIT_FAILURE);
    }
  } else f = stdin;

  c = fgetc (f);
  huff_tree_init (c);
  myputchar (c);

  while ((c = fgetc (f)) != EOF) {
    if (huff_getcode (c, &cs)) {
      huff_code_tostring (&cs);
    } else {
      huff_special_code (&cs);
      huff_code_tostring (&cs);
      myputchar (c);
    }
    huff_tree_modify ((unsigned char)c);
  }

  puts ("");
  return (EXIT_SUCCESS);
}
